package com.leil.fileserver.service;

import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.pdf.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.*;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import java.util.UUID;

@Service
public class PdfGenerateService {

    @Value("${upload.uploadFolder}")
    private String uploadFolder;

    private String getTemplatePath() {
        return this.uploadFolder + "pdfTemplate/";
    }

    private String getOutputPath() {
        return this.uploadFolder + "pdf/";
    }

    public String generatePdf(String tmpName, Map<String, String> dataMap) throws IOException, DocumentException {
        String templatePath = this.getTemplatePath() + tmpName;
        String subFolder = this.getDatePath() + "/";
        String pdfFolder = this.getOutputPath() + subFolder;
        File file = new File(pdfFolder);
        if (!file.exists()) {
            file.mkdirs();
        }
        String fileName = UUID.randomUUID().toString() + ".pdf";
        String outPath = pdfFolder + fileName;
        PdfReader reader;
        FileOutputStream out;
        ByteArrayOutputStream bos;
        PdfStamper stamper;
        out = new FileOutputStream(outPath);// 输出流
        reader = new PdfReader(templatePath);// 读取pdf模板
        bos = new ByteArrayOutputStream();
        stamper = new PdfStamper(reader, bos);
        AcroFields form = stamper.getAcroFields();
        BaseFont bf = BaseFont.createFont("/D:/Uploader/pdfTemplate/simfang.ttf", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
        form.addSubstitutionFont(bf);
        //文字类的内容处理
        for (String key : dataMap.keySet()) {
            String value = dataMap.get(key);
            form.setField(key, value);
        }
        stamper.setFormFlattening(true);// 如果为false，生成的PDF文件可以编辑，如果为true，生成的PDF文件不可以编辑
        stamper.close();

        PdfReader pdfReader = new PdfReader(bos.toByteArray());

        Document doc = new Document();
        PdfCopy copy = new PdfCopy(doc, out);
        doc.open();
        doc.newPage();
        copy.addDocument(pdfReader);
        doc.close();
        return "/static/pdf/" + subFolder + fileName;
    }

    /**
     * 获取当前日期作为存储路径
     * @return
     */
    protected String getDatePath() {
        DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        String targetPath = format.format(new Date());
        return targetPath;
    }

}
